
//
//  UserAccountViewModel.swift
//  01-WeiBo
//
//  Created by 李晓东 on 17/7/1.
//  Copyright © 2017年 PeanutXu. All rights reserved.
//

import Foundation

class UserAccountViewModel {
    
    static let shareUserAccount = UserAccountViewModel()
    var account : UserAccount?
    
    var isLogon : Bool{
        return account?.access_token != nil && !isExpire
    }
    
    var isExpire :Bool{

        let result = account?.expiresDate?.compare(Date())
        if result == ComparisonResult.orderedDescending {
            return false
        }
        // 过期返回 TRUE
        return true
    }
    
    var accessToken:String?{
        if !isExpire {
            let token = account?.access_token
            return token
        }
        return nil
    }
    
    var accountPath:String{
        let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last!
        return (path as NSString).appendingPathComponent("userInfo.plist")
    }
    
    private init() {
        
        account = NSKeyedUnarchiver.unarchiveObject(withFile: accountPath) as? UserAccount
        if isExpire {
            account = nil
        }
        print(account)
    }
}

extension UserAccountViewModel{
    
    func loadUserAccessToken(code:String, finished:@escaping (_ result:Bool) -> ()) {
        NetWorkingTools.shareNetWorkingTools.loadAccessToken(code: code) { (result, error) in
            if result != nil {
                self.account = UserAccount(params: result as! [String: Any])
                self.loadUserInfo(account: self.account!, finished: finished)
            } else {
                finished(false)
            }
        }
    }
    
    func loadUserInfo(account: UserAccount, finished:@escaping (_ result:Bool) -> ())  {
        NetWorkingTools.shareNetWorkingTools.loadUserInfo(uid: account.uid!) { (result, error) in
            if error != nil {
                finished(false)
                return
            }
            guard let r = result as? [String: Any] else {
                finished(false)
                return
            }
            
            finished(true)
        }
    }
    
    private func compareDate() -> Bool{
        let result = account?.expiresDate?.compare(Date())
        if result == ComparisonResult.orderedDescending {
            return false
        }
        return true
    }
}
